package com.sunyard.pcc.shiro.core;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Hewei
 * @Description: shiro session 存入Redis操作类
 * @Date: Created in 11:28 2018/3/12
 */
@Slf4j
@Component
public class RedisShiroSessionDAO extends EnterpriseCacheSessionDAO {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 创建Session, 并存入redis
     * @param session
     * @return
     */
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        String key = getShiroSessionKey(sessionId.toString());
        setShiroSession(key, session);
        return sessionId;
    }


    /**
     * 获取Session
     * @param sessionId
     * @return
     */
    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = super.doReadSession(sessionId);
        if (session == null){
            String key = getShiroSessionKey(sessionId.toString());
            session = getShiroSession(key);
        }
        return session;
    }


    /**
     *更新Session
     * @param session
     */
    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);
        String key = getShiroSessionKey(session.getId().toString());
        setShiroSession(key, session);
    }


    /**
     * 删除Session
     * @param session
     */
    @Override
    protected void doDelete(Session session) {
        super.doDelete(session);
        String key = getShiroSessionKey(session.getId().toString());
        redisTemplate.delete(key);
    }



    private String getShiroSessionKey(String key){
        return "session:" + key;
    }

    /**
     * 将shiro Session存入redis
     * @param key
     * @param session
     */
    private void setShiroSession(String key, Session session){
        redisTemplate.opsForValue().set(key, session);
        //设置过期时间为60分钟
        redisTemplate.expire(key, 60, TimeUnit.MINUTES);
    }


    /**
     * 从redis 获取shiro Session
     * @param key
     * @return
     */
    private Session getShiroSession(String key){
        return (Session) redisTemplate.opsForValue().get(key);
    }
}
